﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

using QRCoder;


namespace TomNet.QRCoder
{
    public interface IQRCodeService
    {
        /// <summary>
        /// 获取QRCode
        /// </summary>
        Bitmap GetQRCode(string plainText, int pixel);
        /// <summary>
        /// 获取QRCode byte[]
        /// </summary>
        byte[] GetQRCodeBytes(string plainText, int pixel);
        /// <summary>
        /// 获取QRCode Base64String
        /// </summary>
        string GetQRCodeString(string plainText, int pixel);
    }

    public class QRCodeService : IQRCodeService
    {
        /// <summary>
        /// 获取QRCode
        /// </summary>
        public Bitmap GetQRCode(string plainText, int pixel)
        {
            var generator = new QRCodeGenerator();
            var qrCodeData = generator.CreateQrCode(plainText, QRCodeGenerator.ECCLevel.Q);
            var qrCode = new QRCode(qrCodeData);
            var bitmap = qrCode.GetGraphic(pixel);
            return bitmap;
        }

        /// <summary>
        /// 获取QRCode byte[]
        /// </summary>
        public byte[] GetQRCodeBytes(string plainText, int pixel)
        {
            var bitmap = GetQRCode(plainText, pixel);
            return ToBytes(bitmap);
        }

        /// <summary>
        /// 获取QRCode Base64String
        /// </summary>
        public string GetQRCodeString(string plainText, int pixel)
        {
            var bytes = GetQRCodeBytes(plainText, pixel);
            return ToBase64(bytes);
        }

        private byte[] ToBytes(Bitmap bitmap)
        {
            using MemoryStream stream = new MemoryStream();
            bitmap.Save(stream, ImageFormat.Jpeg);
            byte[] data = new byte[stream.Length];
            stream.Seek(0, SeekOrigin.Begin);
            stream.Read(data, 0, Convert.ToInt32(stream.Length));
            return data;
        }

        private string ToBase64(byte[] bytes)
        {
            return Convert.ToBase64String(bytes);
        }

    }
}
